<?php
// 本类由系统自动生成，仅供测试用途
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller {

    //注册页
    function register(){
        $user = new \Model\UserModel();
        if(!empty($_POST)){//判断表单是否提交
            $verify = new \Think\Verify();
            if(!$verify->check($_POST['captcha'])){
                $this->assign("info","验证码错误");
            } else {
                $uinfo=$user->where("username='".$_POST["username"]."'")->select();
                if(!empty($uinfo)){
                    $this->assign("info","该用户名已被占用");
                }else{
                    if(!$user -> create()){//只有全部验证通过$z才会为真
                        //验证失败,输出错误信息
                        $error=$user->getError();
                        $uerror=$error["username"]."  ".$error["password"]."  ".$error["password2"];
                        $this->assign("info",$uerror);
                    } else {
                        $rst = $user->add();
                        if ($rst) {
                            $this->redirect("login",null,2,"注册成功，跳转登录页...");
                        } else {
                        }
                    }
                }
            }
        }
        $this -> display();
    }


    //登录页
    function login(){
        if(!empty($_POST)){
            //验证码校验
            $verify = new \Think\Verify();
            if(!$verify->check($_POST['captcha'])){
                $this->assign("info","验证码错误");
            } else {
                //判断用户名和密码，在model模型里边制作一个专门方法进行验证
                $user = new \Model\UserModel();
                $rst = $user -> checkNamePwd($_POST['username'],$_POST['password']);
                if($rst === false){
                    $this->assign("info","用户名或密码错误");
                } else {
                    //登录信息持久化$_SESSION
                    session('username',$rst['username']);
                    session('user_id',$rst['user_id']);
                    //$this ->redirect($url, $params, $delay, $msg)
                    $this -> redirect('Index/index');
                }
            }
        }
        $this -> display();
    }

    //验证码生成
    function verifyImg(){
        $config = array(
            'imageH'    => 50,               // 验证码图片高度
            'imageW'    => 110,
            'fontSize'  => 16,
            'fontttf'   => '4.ttf',              // 验证码字体，不设置随机获取
            'length'    => 4,               // 验证码位数
            'useZh'     => false,           // 使用中文验证码

        );
        $verify = new \Think\Verify($config);
        $verify -> entry();
    }

    public function _empty(){
    echo "404 not found";
    }

    //注销用户
    function logout(){
        session(null);//清空全部session
        $this -> redirect("login");
    }
}